import cv2
import numpy as np


class HistogramEnhance:
    def __init__(self):
        return

    def __call__(self, src, Thistgram=None):
        """
            histogram matching
        """
        if Thistgram is None:
            Thistgram = [i / 255 for i in range(256)]

        h, w = src.shape

        dst = src.tolist()

        src = src.tolist()

        Shistgram = [0 for _ in range(256)]

        for y in range(h):
            for x in range(w):
                Shistgram[src[y][x]] += 1

        for i in range(1, 256):
            Shistgram[i] += Shistgram[i - 1]
        
        W = h * w

        for i in range(0, 256):
            Shistgram[i] /= W

        convet_table = [0 for _ in range(256)]

        Tindex = 0

        for Sindex in range(256):
            while Shistgram[Sindex] > Thistgram[Tindex]:
                Tindex += 1
            convet_table[Sindex] = Tindex
        
        for y in range(h):
            for x in range(w):
                dst[y][x] = convet_table[dst[y][x]]

        dst = np.array(dst).astype('uint8')

        return dst


if __name__ == '__main__':

    SRC = cv2.imread('lena.bmp', cv2.IMREAD_GRAYSCALE)

    def show(winname, img):
        cv2.imshow(winname, img)
        cv2.resizeWindow(winname, 512, 512)
        cv2.waitKey(1)

    show('HISTOGRAMENHANCE', HistogramEnhance()(SRC))
    cv2.waitKey(0)